import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message, Radio, Row } from 'antd';
import { AdvancedSearch, DATA_ENTRY, InputNumberC, ModalC, PrimaryC, RangeDateC, SingleDateC, TableC } from '../../../../comps';
import styles from './index.less';
import accounting from 'accounting';
import moment from 'moment';
import bugImg from '../../../../assets/commom/buy.png';
import sellImg from '../../../../assets/commom/sell.png';
import colorArr from '../../../../css/colors';

@Form.create()
@connect(({ loading, workStationM, globalM, capitalDetailsM }) => ({ loading, workStationM, globalM, capitalDetailsM }))
export default class CashManage extends PureComponent {
  state = {
    isReset: false,
    realParams: {
      combCodes: undefined,
      search_GTE_dataDt: moment().format('YYYYMMDD'),
      search_LTE_dataDt: moment().format('YYYYMMDD'),
      search_EQ_operateType: undefined,
    },
    columns: [
      {
        key: 'date',
        title: '变动时间',
        type: 'date',
      },
      {
        key: 'tradeType',
        title: '变动类型',
        render: (val) => {
          switch (val) {
            case 'Add_Cash':
              return '现金存取';
              break;
            case 'BONUS_CASH':
              return '现金分红';
              break;
            case 'DJPX_FHPX':
              return '分红派息';
              break;
            case 'SELL':
              return '买入';
              break;
            default:
              return '--';
          }
        },
      },
      {
        key: 'flowType',
        title: '流入/流出',
        render: (val) => {
          switch (val) {
            case '1':
              return '流入';
              break;
            case '0':
              return '流出';
              break;
            default:
              return '--';
          }
        },
      },
      {
        key: 'amount',
        title: '金额',
        type: 'money',
      },
      {
        key: 'beforeAmount',
        title: '处理前金额',
        type: 'money',
      },
      {
        key: 'afterAmount',
        title: '处理后金额',
        type: 'money',
      },
    ],
    dataSource: [],
    query: {
      // 查询条件
      startDate: moment().format('YYYY-MM-DD'),
      endDate: moment().format('YYYY-MM-DD'),
    },
    currentPage: 1, // 页码
    pageSize: 10, // 每页数量
    cashIsShow: false, // 现金调整模态框
    value: 1,
    currentCash: undefined,
    // column资金明细判断一致
    operateType: ['48', '44_45', '47_48', '49_50', '52_53', '67', '69', '1006', '1007', '66_67', '68_69'],
  };
  componentDidMount() {
    const { dispatch } = this.props;
    //资产类型字典
    const {
      globalM: {
        dataDictionary: { OPERATE_TYPE_DICT = [] },
      },
    } = this.props;
    dispatch({
      type: 'capitalDetailsM/save',
      payload: {
        typeData: OPERATE_TYPE_DICT,
      },
    });
    this.updateQuery(this.props);
  }

  updateQuery = (currentProps) => {
    //最大值比今天小 则结束日期是最大值，否则是今天
    let endDate = moment().format('YYYYMMDD') - moment(this.props.maxDate).format('YYYYMMDD') > 0 ? moment(this.props.maxDate) : moment();
    //最小值比结束日期往前推一个月 小 则取最小值，否则取往前推一个月的时间
    let startDate = +moment(endDate).subtract(1, 'months').format('YYYYMMDD') - moment(this.props.minDate).format('YYYYMMDD') > 0 ? moment(endDate).subtract(1, 'months') : moment(this.props.minDate);
    // 真实
    if (this.props.workStationM?.CombinationType?.portfolioType === '1') {
      const startDate = this.state.date.props.form.getFieldsValue().search_GTE_dataDt
        ? moment(this.state.date.props.form.getFieldsValue().search_GTE_dataDt).format('YYYYMMDD')
        : moment().format('YYYYMMDD');
      const endDate = this.state.date.props.form.getFieldsValue().search_LTE_dataDt
        ? moment(this.state.date.props.form.getFieldsValue().search_LTE_dataDt).format('YYYYMMDD')
        : moment().format('YYYYMMDD');
      this.setState(
        {
          realParams: {
            combCodes: [currentProps.workStationM?.CombinationType?.portfolioId],
            search_GTE_dataDt: startDate,
            search_LTE_dataDt: endDate,
            search_EQ_operateType: undefined,
          },
          isProductCodeUndefined: currentProps.productCode,
        },
        () => {
          if (currentProps.productCode == undefined) {
            // this.state.date?.setDate([moment(), moment()])
          }
          this.getRealData();
        },
      );
    } else {
      this.setState(
        {
          query: {
            portfolioId: currentProps.productCode,
            startDate: startDate.format('YYYY-MM-DD'),
            endDate: endDate.format('YYYY-MM-DD'),
          },
        },
        () => this.getData(),
      );
    }
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    const init = !this.props.productCode ? '' : JSON.stringify(this.props.productCode);
    const initN = !nextProps.productCode ? '' : JSON.stringify(nextProps.productCode);
    const {
      form: { setFieldsValue },
      minDate,
      maxDate,
    } = this.props;

    const thisPortfolioId = this.props.workStationM?.CombinationType.portfolioId;
    const nextPortfolioId = nextProps.workStationM?.CombinationType.portfolioId;

    //最大值比今天小 则结束日期是最大值，否则是今天
    let endDate = moment().format('YYYYMMDD') - moment(maxDate).format('YYYYMMDD') > 0 ? moment(maxDate) : moment();
    //最小值比结束日期往前推一个月 小 则取最小值，否则取往前推一个月的时间
    let startDate = +moment(endDate).subtract(1, 'months').format('YYYYMMDD') - moment(minDate).format('YYYYMMDD') > 0 ? moment(endDate).subtract(1, 'months') : moment(minDate);
    if (init != initN && thisPortfolioId == nextPortfolioId) {
      setTimeout(() => {
        this.RangeDateRef?.setDate([startDate, endDate]);
      }, 300);
      // 真实
      this.updateQuery(nextProps);
      // if (this.props.workStationM?.CombinationType?.portfolioType === '1') {
      //   const startDate = this.state.date.props.form.getFieldsValue().search_GTE_dataDt
      //     ? moment(this.state.date.props.form.getFieldsValue().search_GTE_dataDt).format('YYYYMMDD')
      //     : moment().format('YYYYMMDD');
      //   const endDate = this.state.date.props.form.getFieldsValue().search_LTE_dataDt
      //     ? moment(this.state.date.props.form.getFieldsValue().search_LTE_dataDt).format('YYYYMMDD')
      //     : moment().format('YYYYMMDD');
      //   this.setState(
      //     {
      //       realParams: {
      //         combCodes: [nextProps.workStationM?.CombinationType?.portfolioId],
      //         search_GTE_dataDt: startDate,
      //         search_LTE_dataDt: endDate,
      //         search_EQ_operateType: undefined,
      //       },
      //       isProductCodeUndefined: nextProps.productCode,
      //     },
      //     () => {
      //       if (nextProps.productCode == undefined) {
      //         // this.state.date?.setDate([moment(), moment()])
      //       }
      //       this.getRealData();
      //     },
      //   );
      // } else {
      //   this.setState(
      //     {
      //       query: {
      //         portfolioId: nextProps.productCode,
      //         startDate: startDate.format('YYYY-MM-DD'),
      //         endDate: endDate.format('YYYY-MM-DD'),
      //       },
      //     },
      //     () => this.getData(),
      //   );
      // }
    }
    if (thisPortfolioId != nextPortfolioId && init == initN) {
      setTimeout(() => {
        this.RangeDateRef?.setDate([startDate, endDate]);
      }, 300);
      // 真实
      if (nextProps.workStationM?.CombinationType?.portfolioType === '1') {
        const startDate = this.state.date?.props.form.getFieldsValue().search_GTE_dataDt
          ? moment(this.state.date.props.form.getFieldsValue().search_GTE_dataDt).format('YYYYMMDD')
          : moment().format('YYYYMMDD');
        const endDate = this.state.date?.props.form.getFieldsValue().search_LTE_dataDt
          ? moment(this.state.date.props.form.getFieldsValue().search_LTE_dataDt).format('YYYYMMDD')
          : moment().format('YYYYMMDD');
        this.setState(
          {
            realParams: {
              combCodes: [nextProps.workStationM?.CombinationType?.portfolioId],
              search_GTE_dataDt: startDate,
              search_LTE_dataDt: endDate,
              search_EQ_operateType: undefined,
            },
            isProductCodeUndefined: nextProps.productCode,
          },
          () => {
            if (nextProps.productCode == undefined) {
              // this.state.date?.setDate([moment(), moment()])
            }
            this.getRealData();
          },
        );
      } else {
        this.setState(
          {
            query: {
              portfolioId: nextProps.productCode,
              startDate: startDate.format('YYYY-MM-DD'),
              endDate: endDate.format('YYYY-MM-DD'),
            },
          },
          () => this.getData(),
        );
      }
    }
    if (this.props.updateState != nextProps.updateState) {
      if (this.state.query.portfolioId) {
        this.getData();
      }
    }
  }
  // 获取现金管理列表
  getData = () => {
    this.props.dispatch({
      type: 'workStationM/queryCashData',
      payload: this.state.query,
      callback: (res) => {
        if (res) {
          this.setState({
            dataSource: res.dataSource,
          });
        } else if ([null, undefined].includes(res)) {
          this.setState({
            dataSource: [],
          });
        }
      },
    });
  };

  // 模态框日期变化响应
  modaldateChange = (e) => {
    this.props.dispatch({
      type: 'workStationM/queryCashData1',
      payload: {
        ...this.state.query,
        startDate: moment(e).format('YYYY-MM-DD'),
        endDate: moment(e).format('YYYY-MM-DD'),
      },
      callback: (res) => {
        if (res) {
          let currentCash = res.dataSource.reduce((p, v) => p + v.afterAmount, 0);
          this.setState({
            currentCash,
          });
        }
      },
    });
  };
  // 日期变化响应
  dateChange = (e) => {
    this.setState(
      {
        query: {
          ...this.state.query,
          startDate: moment(e[0]).format('YYYY-MM-DD'),
          endDate: moment(e[1]).format('YYYY-MM-DD'),
        },
      },
      () => this.getData(),
    );
  };
  //表格排序
  tableChange = (pagination, filt, sorter) => {
    const { realParams, isReset } = this.state;
    const formData = _.cloneDeep(realParams);
    const { dispatch } = this.props;
    this.setState({
      sortedInfo: sorter,
    });
    const data = {
      search_GTE_dataDt: moment(formData.search_GTE_dataDt).format('YYYYMMDD'),
      search_LTE_dataDt: moment(formData.search_LTE_dataDt).format('YYYYMMDD'),
    };
    data.page = {
      current: pagination.current,
      pageSize: pagination.pageSize,
    };
    this.setState({
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
    });
    formData.combCodes ? (data.combCodes = formData.combCodes) : null;
    formData.search_EQ_operateType ? (data.search_EQ_operateType = formData.search_EQ_operateType) : null;
    if (sorter.order !== undefined) {
      data.columnKey = sorter.columnKey;
      if (sorter.order == 'descend') {
        data.order = 'desc';
      } else if (sorter.order == 'ascend') {
        data.order = 'asc';
      } else {
        data.order = '';
      }
    }
    if (isReset) {
      message.warning('您已重置查询字段，请设置条件后执行查询');
      return;
    }
    dispatch({
      type: 'capitalDetailsM/getSearch',
      payload: data,
    });
  };
  // 表格页码响应
  handleTableChange = (pagination, filt, sorter) => {
    const { current, pageSize } = pagination;
    if (this.props.workStationM?.CombinationType?.portfolioType === '1') {
      this.tableChange(pagination, filt, sorter);
      // this.setState({
      //   ...this.state.realParams,
      //   currentPage: current,
      //   pageSize: pageSize,
      // }, () => this.getRealData())
    } else {
      this.setState(
        {
          ...this.state.query,
          currentPage: current,
          pageSize: pageSize,
        },
        () => {
          this.getData();
        },
      );
    }
  };

  // 现金调整
  cashChange = () => {
    this.setState({ cashIsShow: true });
  };
  // 现金调整确定
  handleOk = () => {
    const {
      form: { validateFields },
    } = this.props;
    validateFields((err, fieldsValue) => {
      if (!err) {
        if (fieldsValue.flowType == 0 && fieldsValue.cashAmount > this.state.currentCash) {
          message.error('现金不足');
          return;
        }
        this.props.dispatch({
          type: 'workStationM/adjustCash',
          payload: {
            portfolioId: this.props.productCode,
            date: moment(fieldsValue.date).format('YYYY-MM-DD HH:mm:ss'),
            cashAmount: fieldsValue.cashAmount,
            flowType: fieldsValue.flowType,
          },
          callback: (res) => {
            if (res) {
              this.setState({ cashIsShow: false, currentCash: undefined });
              this.props.changeEdit();
              this.props.changeUpdataState();
            }
          },
        });
      }
    });
  };

  // 现金调整取消
  handleCancel = () => {
    this.setState({ cashIsShow: false, currentCash: undefined });
  };
  // 变动类型点击响应
  onChange = (e) => {
    const {
      form: { setFieldsValue },
    } = this.props;
    if (e) {
      if (e.target.value == 0) {
        setFieldsValue({ date: moment() });
      }
      this.setState({
        value: e.target.value,
      });
    }
  };
  // 现金调整模态框
  showModal = () => {
    const {
      form: { getFieldDecorator },
      minDate,
      maxDate,
    } = this.props;
    const { value } = this.state;
    const formItemLayout = {
      labelCol: {
        span: 8,
      },
      wrapperCol: {
        span: 16,
      },
    };

    return (
      <div>
        <Form>
          <Row>
            <SingleDateC
              form={this.props.form}
              dataIndex='date'
              title='日期：'
              // initialValue={moment()}
              disableBegin={value == 1 ? moment(minDate).subtract(1, 'day') : moment().subtract(1, 'day')}
              disableEnd={value == 1 ? moment(maxDate).add(1, 'day') : moment().add(1, 'day')}
              formItemLayout={formItemLayout}
              onChange={this.modaldateChange}
              rules={[{ required: true, message: '请选择日期' }]}
            />
          </Row>
          <Row>
            <Form.Item label={<span>当日原有现金：</span>} {...formItemLayout}>
              {getFieldDecorator('currentCash', {})(<div>{this.state.currentCash ? accounting.formatNumber(Number(this.state.currentCash), 2) : '--'}</div>)}
            </Form.Item>
          </Row>
          <Row>
            <Form.Item label={<span>变动类型：</span>} {...formItemLayout}>
              {getFieldDecorator('flowType', {
                initialValue: this.state.value,
              })(
                <Radio.Group onChange={this.onChange} value={this.state.value}>
                  <Radio value={1}>存入</Radio>
                  <Radio value={0}>取出</Radio>
                </Radio.Group>,
              )}
            </Form.Item>
          </Row>
          <Row>
            <InputNumberC
              form={this.props.form}
              dataIndex={`cashAmount`}
              title={'变动金额：'}
              precision={2}
              formItemLayout={formItemLayout}
              splitStyle={true}
              min={0}
              max={99999999999}
              rules={[{ required: true, message: '请输入金额' }]}
            />
          </Row>
        </Form>
      </div>
    );
  };

  getRealData = () => {
    this.props.dispatch({
      type: 'capitalDetailsM/getSearch',
      payload: {
        ...this.state.realParams,
        combCodes: this.state.isProductCodeUndefined === undefined ? undefined : this.state.realParams.combCodes,
        page: {
          current: this.state.currentPage,
          pageSize: this.state.pageSize,
        },
      },
    });
  };
  searchDocker = (e) => {
    // 查询
    if (e) {
      const { search_EQ_operateType, search_GTE_dataDt, search_LTE_dataDt } = e;
      this.setState(
        {
          realParams: {
            ...this.state.realParams,
            search_GTE_dataDt: moment(search_GTE_dataDt).format('YYYYMMDD'),
            search_LTE_dataDt: moment(search_LTE_dataDt).format('YYYYMMDD'),
            search_EQ_operateType: search_EQ_operateType ? search_EQ_operateType : undefined,
          },
          currentPage: search_EQ_operateType ? 1 : this.state.currentPage,
        },
        () => this.getRealData(),
      );
    } else {
      // reset
      const copy = JSON.parse(JSON.stringify(this.state.realParams));
      this.setState(
        {
          realParams: {
            ...this.state.realParams,
            search_GTE_dataDt: moment(new Date()).subtract(1, 'months').format('YYYYMMDD'),
            search_LTE_dataDt: moment().format('YYYY-MM-DD'),
            search_EQ_operateType: undefined,
          },
        },
        () => {
          // 不二次查询
          const { search_EQ_operateType, search_GTE_dataDt, search_LTE_dataDt } = this.state.realParams;
          if (copy.search_EQ_operateType !== search_EQ_operateType || copy.search_GTE_dataDt !== search_GTE_dataDt || copy.search_LTE_dataDt !== search_LTE_dataDt) {
            this.getRealData();
          }
        },
      );
    }
  };
  chengeStyle = (text) => {
    const {
      capitalDetailsM: { typeData },
    } = this.props;
    let code = '';
    let test = '';
    if (typeData && typeData.length) {
      typeData.map((item) => {
        if (text == item.code) {
          (code = item.pid), (test = item.value);
        }
      });
    }
    return (
      <div>
        <img src={code == '0' ? bugImg : sellImg} />
        <span style={{ marginLeft: '10px' }}>{test}</span>
      </div>
    );
  };
  redAndGreen = (text, record, num) => {
    const {
      capitalDetailsM: { typeData },
    } = this.props;
    const textColor = colorArr.debtAndProfit.text;
    let code = '';
    if (typeData && typeData.length) {
      typeData.map((item) => {
        if (record.operateType == item.code) {
          code = item.pid;
        }
      });
    }
    const tet = Number(text)
      .toFixed(num)
      .replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
    const colors = code == '1' ? textColor[0] : textColor[1];
    return <span style={{ color: `${colors}` }}>{tet}</span>;
  };
  changeRender = (text, num) => {
    const test = Number(text)
      .toFixed(num)
      .replace(/(\d)(?=(\d{3})+\.)/g, '$1,');

    return test;
  };
  changeColumns = (columns) => {
    let data = columns;
    const { sortedInfo = {} } = this.state;
    if (data && data.length) {
      data.map((item, index, arr) => {
        if (item.key == 'handleDate') {
          // 交易时间排序
          item.sorter = true;
          item.sortOrder = sortedInfo.columnKey == 'handleDate' && sortedInfo.order;
          item.render = (text, record) => {
            return text !== null ? text : record.dataDt;
          };
        }
        if (item.key == 'combName') {
          // 产品名称转为代码-简称
          // item.render = (text, record) => {
          //   return record.rootId + '-' + record.rootName;
          // }
          arr.splice(index, 1);
        }
        if (item.key == 'weight') {
          // 组合名称转为代码-简称
          // item.render = (text, record) => {
          //   return record.combCode + '-' + record.combName;
          // }
          arr.splice(index, 1);
        }
        if (item.key == 'tradingCode') {
          // 证券代码转为代码-简称
          item.render = (text, record) => {
            return record.tradingName ? record.tradingCode + '-' + record.tradingName : record.tradingCode || '--';
          };
        }
        if (item.key == 'operateType') {
          item.render = (text, record) => {
            return this.chengeStyle(text);
          };
        }
        if (item.key == 'balance') {
          (item.align = 'right'),
            (item.render = (text, record) => {
              if (this.state.operateType.some((i) => i == record.operateType)) {
                return text !== null ? this.redAndGreen(text, record, 2) : '--';
              } else {
                return text !== null ? this.redAndGreen(text, record, 4) : '--';
              }
            });
        }
        if (item.key == 'balancepre' || item.key == 'balanceafter') {
          (item.align = 'right'),
            (item.render = (text, record) => {
              if (this.state.operateType.some((i) => i == record.operateType)) {
                return text !== null ? this.changeRender(text, 2) : '--';
              } else {
                return text !== null ? this.changeRender(text, 4) : '--';
              }
            });
        }
        if (item.key == 'currency') {
          item.width = 60;
        }
        if (item.key == 'amount') {
          item.type = 'number';
          item.align = 'right';
          item.render = (text, record) => {
            if (this.state.operateType.some((i) => i == record.operateType)) {
              return '--';
            } else {
              if (isNaN(text)) {
                return text;
              } else {
                return accounting.formatNumber(Number(text), 2);
              }
            }
          };
        }
      });
    }
    return data;
  };
  render() {
    const { columns, dataSource, currentPage, pageSize, cashIsShow } = this.state;
    const {
      minDate,
      maxDate,
      globalM: {
        dataDictionary: { OPERATE_TYPE_DICT = [] },
      },
      workStationM: {
        CombinationType: { portfolioType = undefined },
      },
      capitalDetailsM: { tableData },
    } = this.props;
    const realColumns = this.changeColumns(tableData.data.columns);
    const formItemLayout = {
      labelCol: {
        span: 2,
      },
      wrapperCol: {
        span: 18,
      },
    };
    let startDate = +moment().subtract(1, 'months').format('YYYYMMDD') - moment(minDate).format('YYYYMMDD') > 0 ? moment().subtract(1, 'months') : moment(minDate);
    return (
      <div className={styles.cashManage}>
        {/*判断真实/模拟 */}
        {this.props.workStationM?.CombinationType?.portfolioType === '1' ? (
          <div className={styles.searchCash}>
            <AdvancedSearch
              // parentId={'cashManage'}
              onQuery={(e) => {
                this.searchDocker(e);
              }}
              onClear={(e) => {
                this.searchDocker(e);
              }}
              dataSource={[
                {
                  dataIndex: ['search_GTE_dataDt', 'search_LTE_dataDt'],
                  title: '日期',
                  type: DATA_ENTRY.RANGEDATE,
                  initialValue: [moment(), moment()],
                  onRef: (ref) => {
                    this.state.date = ref;
                  },
                  formItemLayout: {
                    labelCol: {
                      span: this.props.showOnly ? 2 : 4,
                    },
                    wrapperCol: {
                      span: 18,
                    },
                  },
                },
                {
                  dataIndex: 'search_EQ_operateType',
                  title: '变动类型',
                  type: DATA_ENTRY.SELECT,
                  allowClear: true,
                  filterOption: (input, option) => option.props.children.indexOf(input) > -1,
                  dataSource: OPERATE_TYPE_DICT.map((v) => {
                    return { value: v.code, title: v.value };
                  }),
                },
              ]}
            />
          </div>
        ) : (
          <div className={styles.searchCont}>
            <div className={styles.search} style={{ width: '450px' }}>
              <RangeDateC
                form={this.props.form} // form对象
                title='日期'
                dataIndex={['startDate', 'endDate']}
                // initialValue={[moment(startDate), moment(maxDate)]}
                onChange={this.dateChange}
                hasDataBD={moment(minDate)}
                hasDataED={moment(maxDate)}
                formItemLayout={formItemLayout}
                onRef={(ref) => (this.RangeDateRef = ref)}
              />
            </div>
            <div>
              <PrimaryC title={'现金调整'} onClick={this.cashChange} />
            </div>
          </div>
        )}

        <div className={styles.table}>
          <TableC
            columns={portfolioType === '1' ? realColumns : columns}
            dataSource={portfolioType === '1' ? tableData.data.dataSource : dataSource}
            rowKey='id'
            loading={portfolioType === '1' ? this.props.loading.effects['capitalDetailsM/getSearch'] : this.props.loading.effects['workStationM/queryCashData']}
            current={currentPage}
            pageSize={pageSize}
            size={'small'}
            onChange={this.handleTableChange}
            scroll={{ x: 1184, y: 270 }}
            total={portfolioType === '1' ? tableData.data.pageInfo.total : null}
          ></TableC>
        </div>
        {cashIsShow && (
          <div className={styles.modal}>
            <ModalC
              visible={cashIsShow}
              title='现金调整'
              width={350}
              maskClosable={false}
              confirmLoading={this.props.loading.effects['workStationM/adjustCash'] === true}
              onOk={this.handleOk}
              onCancel={this.handleCancel}
            >
              {this.showModal()}
            </ModalC>
          </div>
        )}
      </div>
    );
  }
}
